package com.sptpc.stu.controller;

import com.sptpc.stu.common.response.JSONResponse;
import com.sptpc.stu.model.Major;
import com.sptpc.stu.repository.MajorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/major")
public class MajorController {

    @Autowired
    private MajorRepository majorRepository;

    // 获得所有专业id和信息，可用于新录入学生信息时，选择专业
    @GetMapping(value = "/")
    public List<Major> getAllMajors() {
        // 学生信息写入数据库
        return majorRepository.findAll(Sort.by("mid").descending());
    }

    // 用于前端渲染专业的select
    @GetMapping(value = "/listAll")
    public JSONResponse getAllMajorsForSelect() {
        List<Major> majors = majorRepository.findAll();
        return JSONResponse.ofSuccess(majors);
    }

    // json格式传数据
    @PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Major addNewMajor(@RequestBody Major major) {
        // 专业信息写入数据库
        majorRepository.save(major);
        return major;
    }

    // /major/del/jk001  path
    @DeleteMapping("/del/{mid}")
    public String deleteStudentByPath(
            @PathVariable String mid) {
        // 在数据库中删除对应的专业信息
        Major majorExample = Major.builder()
                .mid(mid).build();
        Example<Major> example = Example.of(majorExample);
        Optional<Major> optionalMajor = majorRepository.findOne(example);
        if (optionalMajor.isPresent()) {
            majorRepository.deleteById(optionalMajor.get().getId());
            return "删除成功";
        } else {
            return "输入的专业编号有误，请查询后再尝试";
        }
    }

}
